package com.handu.luna.core.domain;


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

@SuppressWarnings("rawtypes")
@NoRepositoryBean
public class BaseRepositoryImpl<T extends BasePersistentDomain> extends SimpleJpaRepository<T, Long> implements
		BaseRepository<T> {

	private Log logger = LogFactory.getLog(this.getClass());
	//private EntityManager entityManager;

	public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
		super(domainClass, entityManager);
		//this.entityManager = entityManager;
	}

	public Specification<T> findByField(final String fieldName,final Object field) {
		return new Specification<T>() {
			@Override
			public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {	
				logger.debug("find by " + fieldName + " and " + field);
				return builder.equal(root.get(fieldName), field);
			}
		};
	}

	@Override
	public List<T> find(String fieldName,Object field) {
		return this.findAll(findByField(fieldName,field));
	}	
	
	@Override
	public boolean has(String fieldName,Object field) {
		return count(fieldName,field) > 0;
	}	
	
	@Override
	public long count(String fieldName,Object field) {
		return this.count(findByField(fieldName,field));
	}
}
